package com.bbcare.img.plat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.img.plat.service.IAddPhotoService;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: 图片管理控制类
 * @author: wuyz
 * @createTime: 2017.10.30
 * @descripted: 图片添加、修改及查询等操作
 * @modify:
 */

@Controller
@RequestMapping("/imgMark")
public class AddPhotoController {

    private final Log logger = LogFactory.getLog(AddPhotoController.class);

    @Autowired
    private IAddPhotoService AddPhotoService;

    // 将图片关联到具体患者
    @ResponseBody
    @RequestMapping("/addAssImgUser")
    public ResultModel<Map<String, Object>> addAssImgUser(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in addAssImgUser----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> retMap = new HashMap<String, Object>();
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        chkVar.put("opCode", "操作编码");
        chkVar.put("opType", "操作类型");
        chkVar.put("opNote", "操作备注");
        ToolUtil.checkInputInfo("oprInfo", chkInfo, chkVar);
        chkInfo.put("updateTime", DateUtil.getSysDateA());
        chkInfo.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
        // 设备信息校验
        chkVar.clear();
        chkInfo = ToolUtil.typeCast(mapIn.get("assInfo"));// 关联信息
        // chkVar.put("birthday", "患者出生日期");
        // chkVar.put("gender", "患者性别");
        chkVar.put("userId", "患者id");
        chkVar.put("imgIdList", "文件id列表");
        ToolUtil.checkInputInfo("assInfo", chkInfo, chkVar);

        // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("sessionInfo", sessionMap);

        // 调用业务逻辑
        retMap = AddPhotoService.correlationUser(mapIn);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 根据问卷内容中配置的设备类型查询当前需要检索文件的设备列表
    @ResponseBody
    @RequestMapping("/queryEquipByClassId")
    public ResultModel<Map<String, Object>> queryEquipByClassId(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in queryEquipByClassId----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn);
        chkVar.put("classIdList", "设备类型list");
        ToolUtil.checkInputInfo("classIdList", chkInfo, chkVar);

        // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        // 调用业务逻辑
        mapOut = AddPhotoService.queryEquipByClassId(mapIn);

        return new ResultModel<Map<String, Object>>(mapOut);
    }

    // 根据相关条件查询影像文件 注意：一张影像文件只能被一个患者关联，同一张影像文件不可能属于两个人
    @ResponseBody
    @RequestMapping("/queryImg")
    public ResultModel<Map<String, Object>> queryImg(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in queryImg----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 入参中有文件id，其他参数可不传
        String imgId = (String) mapIn.get("imgId");
        // 操作信息校验
        Map<String, Object> mapOut = new HashMap<String, Object>();
        if (StringUtils.isBlank(imgId)) {
            List<Object> equipIdList = ToolUtil.typeCast(mapIn.get("equipIdList"));
            ToolUtil.checkInputList("设备id列表", equipIdList, null);
        }

        if (StringUtils.isBlank(imgId)) {
            // 分页信息校验
            ToolUtil.checkPageInfo(mapIn);
        }

        // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        // 针对Datatable特殊处理
        String jsonStr = (String) mapIn.get(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (StringUtils.isNotBlank(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            mapIn.put("start", jsonTable.getIntValue("start"));
            mapIn.put("end", jsonTable.getIntValue("length"));
        }
        // 调用业务逻辑
        mapOut = AddPhotoService.queryImg(mapIn);
        // 针对Datatable特殊处理
        if (StringUtils.isNotBlank(jsonStr)) {
            mapOut.put("draw", draw);
            mapOut.put("recordsTotal", mapOut.get("total"));
            mapOut.put("recordsFiltered", mapOut.get("total"));
        }

        return new ResultModel<Map<String, Object>>(mapOut);
    }



    // 查询文件信息
    @ResponseBody
    @RequestMapping("/queryNffyyFile")
    public Map<String, Object> queryNffyyFile(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in queryNffyyFile----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        Map<String, Object> mapOut = new HashMap<String,Object>();
        Integer page = 1;
        Integer rows = 20;
        if (!MapUtils.isEmpty(mapIn)) {
            page = (Integer) mapIn.get("page");
            if (null == page || page <= 0) {
                page = 1;
            }
            rows = (Integer) mapIn.get("rows");
            if (null == rows || rows <= 0) {
                rows = 20;
            }
        }
        mapIn.put("start", (page - 1) * rows);
        mapIn.put("end", rows);

        // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        // 针对Datatable特殊处理
        String jsonStr = (String) mapIn.get(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (StringUtils.isNotBlank(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            mapIn.put("start", jsonTable.getIntValue("start"));
            mapIn.put("end", jsonTable.getIntValue("length"));
        }
        // 调用业务逻辑
        mapOut = AddPhotoService.queryImg(mapIn);
        // 针对Datatable特殊处理
        if (StringUtils.isNotBlank(jsonStr)) {
            mapOut.put("draw", draw);
            mapOut.put("recordsTotal", mapOut.get("total"));
            mapOut.put("recordsFiltered", mapOut.get("total"));
        }

        return mapOut;
    }



    // 将图片与患者关联关系解除
    @ResponseBody
    @RequestMapping("/removeAssImgUser")
    public ResultModel<Map<String, Object>> removeAssImgUser(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in removeAssImgUser----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> retMap = new HashMap<String, Object>();
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        chkVar.put("opCode", "操作编码");
        chkVar.put("opType", "操作类型");
        chkVar.put("opNote", "操作备注");
        ToolUtil.checkInputInfo("oprInfo", chkInfo, chkVar);
        chkInfo.put("updateTime", DateUtil.getSysDateA());
        chkInfo.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
        // 设备信息校验
        chkVar.clear();
        chkInfo = ToolUtil.typeCast(mapIn.get("assInfo"));// 关联信息
        chkVar.put("imgId", "文件id");
        chkVar.put("userId", "患者id");
        ToolUtil.checkInputInfo("assInfo", chkInfo, chkVar);

        // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("sessionInfo", sessionMap);

        // 调用业务逻辑
        retMap = AddPhotoService.removeAssImgUser(mapIn);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 自动将用户关联到患者
    @ResponseBody
    @RequestMapping("/imgClientApi/addAssImgUserAuto")
    public ResultModel<Map<String, Object>> addAssImgUserAuto(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in addAssImgUserAuto----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> retMap = new HashMap<String, Object>();
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        chkVar.put("opCode", "操作编码");
        chkVar.put("opType", "操作类型");
        chkVar.put("opNote", "操作备注");
        ToolUtil.checkInputInfo("oprInfo", chkInfo, chkVar);
        chkInfo.put("updateTime", DateUtil.getSysDateA());
        chkInfo.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
        // 设备信息校验
        chkVar.clear();
        chkInfo = ToolUtil.typeCast(mapIn.get("assInfo"));// 关联信息
        // chkVar.put("birthday", "患者出生日期");
        // chkVar.put("gender", "患者性别");
        chkVar.put("userId", "患者id");
        chkVar.put("imgIdList", "文件id列表");
        ToolUtil.checkInputInfo("assInfo", chkInfo, chkVar);

        // 调用业务逻辑
        retMap = AddPhotoService.correlationUser(mapIn);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 查询患者关联的图片信息
    @ResponseBody
    @RequestMapping("/imgClientApi/selectImgUser")
    public ResultModel<Map<String, Object>> selectImgUser(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.info("in selectImgUser----arg==" + arg);
        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        Map<String, Object> mapOut = new HashMap<String,Object>();
        //用户id
        String userId=  (String) mapIn.get("userId");
        //查询类型
        //String type=  (String) mapIn.get("type");
        if(StringUtils.isBlank(userId)) {
        	throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    Constants.API_INPUT_PARAMS_DATA_ERROR + "，" +"用户id为空！"));
        }

        /*if(StringUtils.isBlank(type)) {
        	throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    Constants.API_INPUT_PARAMS_DATA_ERROR + "，" +"查询类型为空！"));
        }*/

        if(mapIn.get("page")!=null) {
        	 Integer page = 1;
             Integer rows = 20;
             if (!MapUtils.isEmpty(mapIn)) {
                 page = (Integer) mapIn.get("page");
                 if (null == page || page <= 0) {
                     page = 1;
                 }
                 rows = (Integer) mapIn.get("rows");
                 if (null == rows || rows <= 0) {
                     rows = 20;
                 }
             }
             mapIn.put("start", (page - 1) * rows);
             mapIn.put("end", rows);
        }

      /*  // 登录信息，从session中获取
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));*/

        // 针对Datatable特殊处理
        String jsonStr = (String) mapIn.get(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (StringUtils.isNotBlank(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            mapIn.put("start", jsonTable.getIntValue("start"));
            mapIn.put("end", jsonTable.getIntValue("length"));
        }
        // 调用业务逻辑
        mapOut = AddPhotoService.selectImgUser(mapIn);
        // 针对Datatable特殊处理
        if (StringUtils.isNotBlank(jsonStr)) {
            mapOut.put("draw", draw);
            mapOut.put("recordsTotal", mapOut.get("total"));
            mapOut.put("recordsFiltered", mapOut.get("total"));
        }

        return new ResultModel<Map<String, Object>>(mapOut);
    }

}
